package com.yl.immodule.util;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.util.LruCache;
import android.widget.ImageView;

import java.io.File;
import java.lang.ref.WeakReference;
import java.net.URL;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class ImageLoader {
    private static final String TAG = "ImageLoader";
    
    // 创建一个线程池，限制并发任务数量
    private static final Executor THREAD_POOL_EXECUTOR = Executors.newFixedThreadPool(3);
    
    // 内存缓存
    private static final LruCache<String, Bitmap> memoryCache;
    
    static {
        // 计算可用最大内存
        final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
        // 使用可用内存的1/8作为图片缓存
        final int cacheSize = maxMemory / 8;
        
        memoryCache = new LruCache<String, Bitmap>(cacheSize) {
            @Override
            protected int sizeOf(String key, Bitmap bitmap) {
                // 计算bitmap大小，单位KB
                return bitmap.getByteCount() / 1024;
            }
        };
    }
    
    // 添加bitmap到内存缓存
    private static void addBitmapToMemoryCache(String key, Bitmap bitmap) {
        if (getBitmapFromMemoryCache(key) == null && bitmap != null) {
            memoryCache.put(key, bitmap);
        }
    }
    
    // 从内存缓存获取bitmap
    private static Bitmap getBitmapFromMemoryCache(String key) {
        return memoryCache.get(key);
    }
    
    public static void loadThumbnail(String imagePath, ImageView imageView, int width, int height) {
        if (imagePath == null || imageView == null) {
            Log.e(TAG, "imagePath或imageView为空");
            return;
        }
        
        // 尝试从缓存中获取
        Bitmap cachedBitmap = getBitmapFromMemoryCache(imagePath);
        if (cachedBitmap != null) {
            Log.d(TAG, "从缓存加载图片: " + imagePath);
            imageView.setImageBitmap(cachedBitmap);
            return;
        }
        
        // 异步加载图片
        BitmapWorkerTask task = new BitmapWorkerTask(imageView, width, height);
        task.executeOnExecutor(THREAD_POOL_EXECUTOR, imagePath);
    }
    
    // 异步任务加载图片
    private static class BitmapWorkerTask extends AsyncTask<String, Void, Bitmap> {
        private final WeakReference<ImageView> imageViewReference;
        private final int targetWidth;
        private final int targetHeight;
        private String imagePath;
        
        BitmapWorkerTask(ImageView imageView, int width, int height) {
            // 使用弱引用避免内存泄漏
            imageViewReference = new WeakReference<>(imageView);
            this.targetWidth = width;
            this.targetHeight = height;
        }
        
        @Override
        protected Bitmap doInBackground(String... params) {
            imagePath = params[0];
            
            try {
                Bitmap bitmap = null;
                
                // 检查是否是网络URL
                if (imagePath.startsWith("http://") || imagePath.startsWith("https://")) {
                    Log.d(TAG, "加载网络图片: " + imagePath);
                    try {
                        URL url = new URL(imagePath);
                        bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
                    } catch (Exception e) {
                        Log.e(TAG, "加载网络图片失败: " + e.getMessage());
                        return null;
                    }
                } else {
                    // 检查文件是否存在
                    File imageFile = new File(imagePath);
                    if (!imageFile.exists()) {
                        Log.e(TAG, "图片文件不存在: " + imagePath);
                        return null;
                    }
                    
                    Log.d(TAG, "加载本地图片: " + imagePath);
                    
                    // 首先获取图片尺寸
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inJustDecodeBounds = true;
                    BitmapFactory.decodeFile(imagePath, options);
                    
                    // 计算缩放比例
                    options.inSampleSize = calculateInSampleSize(options, targetWidth, targetHeight);
                    
                    // 加载实际图片
                    options.inJustDecodeBounds = false;
                    bitmap = BitmapFactory.decodeFile(imagePath, options);
                }
                
                // 添加到缓存
                if (bitmap != null) {
                    addBitmapToMemoryCache(imagePath, bitmap);
                }
                
                return bitmap;
            } catch (Exception e) {
                Log.e(TAG, "加载图片异常: " + e.getMessage());
                return null;
            }
        }
        
        @Override
        protected void onPostExecute(Bitmap bitmap) {
            if (bitmap != null) {
                final ImageView imageView = imageViewReference.get();
                if (imageView != null) {
                    imageView.setImageBitmap(bitmap);
                }
            }
        }
        
        private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
            // 原始图片的宽高
            final int height = options.outHeight;
            final int width = options.outWidth;
            int inSampleSize = 1;
            
            if (height > reqHeight || width > reqWidth) {
                // 计算宽高缩放比例
                final int heightRatio = Math.round((float) height / (float) reqHeight);
                final int widthRatio = Math.round((float) width / (float) reqWidth);
                
                // 选择较小的比例作为采样率，确保最终图片尺寸大于等于目标尺寸
                inSampleSize = Math.min(heightRatio, widthRatio);
            }
            
            return inSampleSize;
        }
    }
} 